import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'

export async function POST(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions)
    
    if (!session?.user) {
      return NextResponse.json({ message: '未授权' }, { status: 401 })
    }

    // 只有教师和管理员可以创建分组
    if (session.user.role !== 'TEACHER' && session.user.role !== 'ADMIN') {
      return NextResponse.json({ message: '权限不足' }, { status: 403 })
    }

    const body = await request.json()
    const { name, description, experimentId, studentIds, leaderId } = body

    if (!name || !experimentId || !studentIds || studentIds.length === 0) {
      return NextResponse.json({ message: '缺少必要参数' }, { status: 400 })
    }

    // 如果指定了组长，验证组长是否在学生列表中
    if (leaderId && !studentIds.includes(leaderId)) {
      return NextResponse.json({ message: '指定的组长必须是组成员之一' }, { status: 400 })
    }

    // 验证实验是否存在且属于当前用户
    const experiment = await prisma.experiment.findFirst({
      where: {
        id: experimentId,
        createdById: session.user.id
      }
    })

    if (!experiment) {
      return NextResponse.json({ message: '实验不存在或无权限' }, { status: 404 })
    }

    // 验证学生是否已授权访问该实验
    const authorizedStudents = await prisma.experimentAuthorization.findMany({
      where: {
        experimentId,
        studentId: {
          in: studentIds
        }
      }
    })

    if (authorizedStudents.length !== studentIds.length) {
      return NextResponse.json({ message: '部分学生未授权访问该实验' }, { status: 400 })
    }

    // 创建分组
    const group = await prisma.group.create({
      data: {
        name,
        description,
        experimentId,
        members: {
          create: studentIds.map((studentId: string) => ({
            userId: studentId,
            role: leaderId ? (studentId === leaderId ? 'LEADER' : 'MEMBER') : (studentIds[0] === studentId ? 'LEADER' : 'MEMBER')
          }))
        }
      },
      include: {
        members: {
          include: {
            user: {
              select: {
                id: true,
                name: true,
                email: true
              }
            }
          }
        }
      }
    })

    return NextResponse.json({ group })
  } catch (error) {
    console.error('创建分组失败:', error)
    return NextResponse.json({ message: '创建分组失败' }, { status: 500 })
  }
} 